package com.example.goodrubish.Garbage;
// DatabaseHelper.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class DatabaseHelper extends SQLiteOpenHelper {
    private static String DATABASE_NAME = "question.db";
    private final Context context;
    private SQLiteDatabase database;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建数据库时的初始化操作
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 数据库升级操作
    }

    public SQLiteDatabase openDatabase() {
        // 检查数据库文件是否存在
        File databasePath = context.getDatabasePath(DATABASE_NAME);
        if (!databasePath.exists()) {
            // 数据库文件不存在，从 assets 目录复制
            try {
                copyDatabaseFromAssets();
            } catch (IOException e) {
                Log.e("DatabaseHelper", "无法复制数据库文件", e);
                return null;
            }
        }
        // 打开数据库
        database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
        return database;
    }

    private void copyDatabaseFromAssets() throws IOException {
        // 从 assets 目录复制数据库文件到内部存储
        InputStream is = context.getAssets().open(DATABASE_NAME);
        String outFileName = context.getDatabasePath(DATABASE_NAME).getAbsolutePath();
        OutputStream os = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        os.flush();
        os.close();
        is.close();
    }
}